//
//  CCAlert.m
//  CCKit
//
//  Created by tucici on 2019/3/18.
//  Copyright © 2019 tucici. All rights reserved.
//

#import "CCAlert.h"
#import <objc/runtime.h>
#import "NSString+category_CCKit.h"
@interface CCAlert ()

@end

@implementation CCAlert

+ (void)showMessage:(NSString *)message hidden:(nullable void(^)(void))hidden
{
    CCAlertController *alertVC = [CCAlertController alertControllerWithTitle:nil
                                                                     message:message
                                                              preferredStyle:UIAlertControllerStyleAlert];
    NSMutableAttributedString *alertVCMessage = [[NSMutableAttributedString alloc] initWithString:message];
    [alertVCMessage addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15 weight:UIFontWeightLight] range:NSMakeRange(0, message.length)];
    [alertVC setValue:alertVCMessage forKey:@"attributedMessage"];
    
    [self presentVC:alertVC complete:^{
        dispatch_time_t delaytime = dispatch_time(DISPATCH_TIME_NOW, (int64_t) 1.0 *NSEC_PER_SEC);
        dispatch_after(delaytime, dispatch_get_main_queue(), ^{
            alertVC.view.hidden = YES;
            [alertVC dismissViewControllerAnimated:YES completion:^{
                if (hidden)
                {
                    hidden();
                }
            }];
        });
    }];
}
/// 特殊VC转场动画的情况下，不太好找到当前显示的VC，可以传入指定的VC，让CCAlert在这个指定的VC推出
/// @param message CCAlert的text
/// @param viewController 指定的VC
/// @param hidden 隐藏完成，CCAlert的回调
+ (void)showMessage:(NSString *)message inViewController:(UIViewController *)viewController hidden:(void (^)(void))hidden
{
    CCAlertController *alertVC = [CCAlertController alertControllerWithTitle:nil
                                                                     message:message
                                                              preferredStyle:UIAlertControllerStyleAlert];
    NSMutableAttributedString *alertVCMessage = [[NSMutableAttributedString alloc] initWithString:message];
    [alertVCMessage addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15 weight:UIFontWeightLight] range:NSMakeRange(0, message.length)];
    [alertVC setValue:alertVCMessage forKey:@"attributedMessage"];

    [viewController presentViewController:alertVC animated:YES completion:^{
        dispatch_time_t delaytime = dispatch_time(DISPATCH_TIME_NOW, (int64_t) 1.0 *NSEC_PER_SEC);
        dispatch_after(delaytime, dispatch_get_main_queue(), ^{
            alertVC.view.hidden = YES;
            [alertVC dismissViewControllerAnimated:YES completion:^{
                if (hidden)
                {
                    hidden();
                }
            }];
        });
    }];
}

+ (void)showMessage:(NSString *)message title:(nullable NSString *)title enter:(nullable void(^)(void))enter
{
    title = (title == nil)?@"":title;
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title
                                                                     message:message
                                                              preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *enterBtn = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                     handler:^(UIAlertAction * _Nonnull action) {
                                                         if (enter)
                                                             enter();
                                                     }];
    
    [alertVC addAction:enterBtn];
    [self presentVC:alertVC complete:nil];
}
+ (void)showMessage:(NSString *)message title:(nullable NSString *)title
        leftBtnText:(nullable NSString *)leftText rightBtnText:(nullable NSString *)rightText
          leftblock:(nullable void(^)(void))left rightBlock:(nullable void(^)(void))right
{
    title = (title == nil)?@"":title;
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title
                                                                     message:message
                                                              preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *leftBtn = [UIAlertAction actionWithTitle:leftText style:UIAlertActionStyleDefault
                                                    handler:^(UIAlertAction * _Nonnull action) {
                                                        if (left)
                                                            left();
                                                    }];
    UIAlertAction *rightBtn = [UIAlertAction actionWithTitle:rightText style:UIAlertActionStyleDefault
                                                     handler:^(UIAlertAction * _Nonnull action) {
                                                         if (right)
                                                             right();
                                                     }];
    [alertVC addAction:leftBtn];
    [alertVC addAction:rightBtn];
    [self presentVC:alertVC complete:nil];
}
+ (void)sheet:(nullable NSString *)message title:(nullable NSString *)title sheetTitles:(nullable NSArray*)sheets block:(nullable void(^) (int index))block
{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title
                                                                     message:message
                                                              preferredStyle:UIAlertControllerStyleActionSheet];
  
    NSMutableArray *newsheets = [NSMutableArray arrayWithArray:sheets];
    [newsheets addObject:@"取消"];
    for (int i = 0; i < newsheets.count; i++)
    {
        UIAlertActionStyle style = (i < sheets.count)?UIAlertActionStyleDefault:UIAlertActionStyleCancel;
        UIAlertAction *action = [UIAlertAction actionWithTitle:newsheets[i] style:style
                                                       handler:^(UIAlertAction * _Nonnull action) {
                                                           if (i < sheets.count)
                                                           {
                                                               if (block)
                                                                   block(i);
                                                           }
                                                           else
                                                               [self dismissViewController];
                                                       }];
//        [action setValue:RGBA(233, 78, 96, 1) forKey:@"titleTextColor"];
        [alertVC addAction:action];
    }
    [self presentVC:alertVC complete:nil];
}

+ (void)presentVC:(UIViewController *)VC complete:(nullable void(^)(void))completion
{
//    UIViewController *currentVC = [self currentVC];
//    if (currentVC)
//    {
//        [currentVC presentViewController:VC animated:YES completion:completion];
//    }
}
+ (void)dismissViewController
{
//    UIViewController *currentVC = [self currentVC];
//    if (currentVC)
//    {
//        [currentVC dismissViewControllerAnimated:YES completion:nil];
//    }
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

@interface CCAlertController ()
@property (nonatomic, strong) UILabel *customLabel;
@property (nonatomic, assign) CGFloat defaultWidth;
@end
@implementation CCAlertController
- (void)viewDidLoad {
    [super viewDidLoad];
    for (UIView *view in [self.view subviews])
    {
        view.layer.cornerRadius = 5.0;
        view.layer.borderColor = [UIColor lightGrayColor].CGColor;
        view.layer.borderWidth = 0.3;
        view.layer.masksToBounds = YES;
        [view removeFromSuperview];
    }
}
- (UILabel *)customLabel
{
    if (!_customLabel)
    {
        _customLabel = [[UILabel alloc]initWithFrame:CGRectZero];
        _customLabel.bounds = CGRectMake(0.0, 0.0, 150, 40);
        _customLabel.center = CGPointZero;
        _customLabel.backgroundColor = [UIColor whiteColor];
        _customLabel.layer.cornerRadius = 5.0;
        _customLabel.layer.borderColor = [UIColor lightGrayColor].CGColor;
        _customLabel.layer.borderWidth = 0.3;
        _customLabel.layer.masksToBounds = YES;
        _customLabel.textAlignment = NSTextAlignmentCenter;
        [self setupCustomLabelText];
        [self.view addSubview:_customLabel];
    }
    return _customLabel;
}
- (CGFloat)defaultWidth
{
    return MIN(320,MIN([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) - 60);
}
- (void)setupCustomLabelText
{
    UIFont *font = [UIFont systemFontOfSize:15 weight:UIFontWeightLight];
    CGSize size = [self.message sizeWithAttributes:@{NSFontAttributeName:font}];
    if (size.width > self.defaultWidth)
    {
        CGSize size = [self.message sizeWithFont:[UIFont systemFontOfSize:15 weight:UIFontWeightLight] inWidth:self.defaultWidth];
        _customLabel.bounds = CGRectMake(0.0, 0.0, size.width, size.height + 20);
        _customLabel.numberOfLines = 0;
    }
    else
    {
        _customLabel.bounds = CGRectMake(0.0, 0.0, ceil(size.width) + 40, 40);
    }
    NSMutableAttributedString *alertVCMessage = [[NSMutableAttributedString alloc] initWithString:self.message];
    [alertVCMessage addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, self.message.length)];
    [alertVCMessage addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, self.message.length)];
    _customLabel.attributedText = alertVCMessage;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.customLabel.hidden = NO;
}
@end
